import CryptoJS from "crypto-js";
import { ref, onMounted, onUnmounted } from "vue";

const modelDomain = "generalv3.5"; // https://www.xfyun.cn/doc/spark/Web.html#_1-%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
//APPID，APISecret，APIKey在https://console.xfyun.cn/services/cbm这里获取
const APPID = "f94e49e9";
const API_SECRET = "MDAwMDhhZjhlMDg5YjIxNTRhMzczMGQ2";
const API_KEY = "e3503c5321d225514113ea930164a006";

function getWebsocketUrl() {
  return new Promise((resolve, reject) => {
    var apiKey = API_KEY;
    var apiSecret = API_SECRET;

    // var url = 'wss://' + httpUrl.host + httpUrl.pathname
    var url = "wss://spark-api.xf-yun.com/v3.5/chat";

    var host = location.host;
    var date = new Date().toGMTString();
    var algorithm = "hmac-sha256";
    var headers = "host date request-line";
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${"/v3.5/chat"} HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    resolve(url);
  });
}

// 按照上面写一个useChat
export function useChat() {
  let total_res = ref("");
  const messages = ref([
    {
      role: "system",
      content:
        "你是AI健康管家，患者可以简单描述自己的情况，你可以推断他的病状情况，并给出建议(每次回答字数限制在100以内)",
    },
    // {
    //   role: "user",
    //   content:
    //     "我最近总是感觉很累，而且晚上睡不着觉，白天没有精神，我该怎么办？",
    // },
    // {
    //   role: "assistant",
    //   content: "你可能是得了抑郁症，建议你去医院看看",
    // },
    // {
    //   role: "user",
    //   content: "比如我还得注意些什么呢？",
    // },
  ]);

  class TTSRecorder {
    constructor({ appId = APPID } = {}) {
      this.appId = "f94e49e9";
      this.status = "init";
      this.onWillStatusChange = null;
    }

    // 修改状态
    setStatus(status) {
      this.onWillStatusChange && this.onWillStatusChange(this.status, status);
      this.status = status;
    }

    // 连接websocket
    connectWebSocket() {
      this.setStatus("ttsing");
      return getWebsocketUrl().then((url) => {
        let ttsWS;
        console.log(url);

        if ("WebSocket" in window) {
          ttsWS = new WebSocket(url);
        } else if ("MozWebSocket" in window) {
          ttsWS = new MozWebSocket(url);
        } else {
          alert("浏览器不支持WebSocket");
          return;
        }
        this.ttsWS = ttsWS;
        ttsWS.onopen = (e) => {
          this.webSocketSend();
        };
        ttsWS.onmessage = (e) => {
          this.result(e.data);
        };
        ttsWS.onerror = (e) => {
          clearTimeout(this.playTimeout);
          this.setStatus("error");
          alert("WebSocket报错，请f12查看详情");
          console.error(
            `详情查看：${encodeURI(url.replace("wss:", "https:"))}`
          );
        };
        ttsWS.onclose = (e) => {
          console.log(e);
        };
      });
    }

    // websocket发送数据
    webSocketSend() {
      var params = {
        header: {
          app_id: this.appId,
          uid: "1234567890",
        },
        parameter: {
          chat: {
            domain: modelDomain,
            temperature: 0.5,
            max_tokens: 2048,
          },
        },
        payload: {
          message: {
            text: messages.value,
          },
        },
      };
      this.ttsWS.send(JSON.stringify(params));
    }

    start() {
      total_res.value = ""; // 请空回答历史
      this.connectWebSocket();
    }

    // websocket接收数据的处理
    result(resultData) {
      let jsonData = JSON.parse(resultData);
      total_res.value = total_res.value + jsonData.payload.choices.text[0].content;

      // 处理total_res中的Markdown格式，去除
      total_res.value = total_res.value.replace(/[\*#\-]/g, "");

      // 提问失败
      if (jsonData.header.code !== 0) {
        alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
        console.error(`${jsonData.header.code}:${jsonData.header.message}`);
        return;
      }
      if (jsonData.header.code === 0 && jsonData.header.status === 2) {
        this.ttsWS.close();
        bigModel.setStatus("init");

        // 将messages中的最后一个元素的content设置为total_res.value
        messages.value[messages.value.length - 1].content = ref(total_res.value);
      }
    }
  }

  let bigModel = new TTSRecorder();
  bigModel.onWillStatusChange = function (oldStatus, status) {
    // 可以在这里进行页面中一些交互逻辑处理：按钮交互等
  };
  function start() {
    if (["init", "endPlay", "errorTTS"].indexOf(bigModel.status) > -1) {
      bigModel.start();
    }
  }

  return {
    total_res,
    messages,
    start,
    bigModel
  };
}


export function useChat2() {
  let result = ref("");
  const chat_history = ref("");
  class TTSRecorder {
    constructor({ appId = APPID } = {}) {
      this.appId = "f94e49e9";
      this.status = "init";
      this.onWillStatusChange = null;
    }

    // 修改状态
    setStatus(status) {
      this.onWillStatusChange && this.onWillStatusChange(this.status, status);
      this.status = status;
    }

    // 连接websocket
    connectWebSocket() {
      this.setStatus("ttsing");
      return getWebsocketUrl().then((url) => {
        let ttsWS;
        console.log(url);

        if ("WebSocket" in window) {
          ttsWS = new WebSocket(url);
        } else if ("MozWebSocket" in window) {
          ttsWS = new MozWebSocket(url);
        } else {
          alert("浏览器不支持WebSocket");
          return;
        }
        this.ttsWS = ttsWS;
        ttsWS.onopen = (e) => {
          this.webSocketSend();
        };
        ttsWS.onmessage = (e) => {
          this.result(e.data);
        };
        ttsWS.onerror = (e) => {
          clearTimeout(this.playTimeout);
          this.setStatus("error");
          alert("WebSocket报错，请f12查看详情");
          console.error(
            `详情查看：${encodeURI(url.replace("wss:", "https:"))}`
          );
        };
        ttsWS.onclose = (e) => {
          console.log(e);
        };
      });
    }

    // websocket发送数据
    webSocketSend() {
      var params = {
        header: {
          app_id: this.appId,
          uid: "1234567890",
        },
        parameter: {
          chat: {
            domain: modelDomain,
            temperature: 0.5,
            max_tokens: 2048,
          },
        },
        payload: {
          message: {
            text: [
              {
                role: "system",
                content:
                  "你是一个AI健康助手，你可以根据患者和专业AI的对话，给出三条简短的用户模拟问题（每条不超过15个字），用来帮助用户快速描述自己的情况",
              },
              {
                role: "user",
                content:"如下是用户与AI的对话，给用户输出三条用户可能会问到AI的问题："+ chat_history.value,
              },
            ],
          },
        },
      };
      this.ttsWS.send(JSON.stringify(params));
    }

    start() {
      result.value = ""; // 请空回答历史
      this.connectWebSocket();
    }

    // websocket接收数据的处理
    result(resultData) {
      let jsonData = JSON.parse(resultData);
      result.value = result.value + jsonData.payload.choices.text[0].content;

      // 提问失败
      if (jsonData.header.code !== 0) {
        alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
        console.error(`${jsonData.header.code}:${jsonData.header.message}`);
        return;
      }
      if (jsonData.header.code === 0 && jsonData.header.status === 2) {
        this.ttsWS.close();
        bigModel.setStatus("init");
      }
    }
  }

  let bigModel = new TTSRecorder();
  bigModel.onWillStatusChange = function (oldStatus, status) {
    // 可以在这里进行页面中一些交互逻辑处理：按钮交互等
  };
  function startAI() {
    if (["init", "endPlay", "errorTTS"].indexOf(bigModel.status) > -1) {
      bigModel.start();
    }
  }

  return {
    result,
    startAI,
    chat_history,
    bigModel
  };
}